package com.sunday.common.mq.kafka.study.spring.e6_Receiving_Messages_1;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * {@link org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration}
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class MQApi {

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @Getter
    private final String topic = "topic1";

    @GetMapping("/send/{topic}/{key}")
    public void send(@PathVariable String topic, @PathVariable String key) throws ExecutionException, InterruptedException {
        CompletableFuture<SendResult<Object, Object>> future;
        future = kafkaTemplate.send(topic, key, key);
        log.info("{}", future.get());
    }

    @GetMapping("/batch/{topic}")
    public void batch(@PathVariable String topic) {
        CompletableFuture<SendResult<Object, Object>> future;
        for (int i = 0; i < 10; i++) {
            future = kafkaTemplate.send(topic, i + "", i + "");
            future.whenComplete((result, throwable) -> log.info("[{}] result : {}, throwable : {}", topic, result, throwable));
        }
    }


    @KafkaListener(
            id = "myId_1",
//            topics = "topic1",
            clientIdPrefix = "TEST",
            containerFactory = "kafkaListenerContainerFactory",
            /** https://docs.spring.io/spring-kafka/docs/current/reference/html/#annotation-properties */
            // 本类配置
//            topics = "#{__listener.topic}",
//            groupId = "#{__listener.topic}.group",
            /** beanRef = "__x"  */
            // 外部类配置
            beanRef = "myListener",
            topics = "#{myListener.topic}",
            groupId = "#{myListener.topic}.group"
    )
    public void listen1(String in) {
        log.info("======================== {}", in);
    }

}
